﻿using System;
using System.Diagnostics;
using Microsoft.Build.Framework;

namespace DotNet.DevOps.Tasks.Util
{
    class MSBuildLogger : ILog
    {
        private ITask task;
        private string taskName;

        public MSBuildLogger(ITask task)
        {
            this.task = task;
            taskName = task.GetType().Name;
        }

        public void LogInfo(string msg)
        {
            var stampedMsg = string.Format("[{0}] - {1}", DateTime.Now.TimeOfDay, msg);

            if (task.BuildEngine != null)
            {
                task.BuildEngine.LogMessageEvent(new BuildMessageEventArgs(stampedMsg, "Info", taskName, MessageImportance.Normal));
            }
            else
            {
                Console.WriteLine(stampedMsg);
            }
        }

        public void LogWarning(string msg)
        {
            var stampedMsg = string.Format("[{0}] - {1}", DateTime.Now.TimeOfDay, msg);

            if (task.BuildEngine != null)
            {
                task.BuildEngine.LogWarningEvent(new BuildWarningEventArgs("Warning", "Warning", "", 0, 0, 0, 0, stampedMsg,
                                                                           "Warning", taskName));
            }
            else
            {
                WriteLine(stampedMsg, ConsoleColor.Yellow);
            }
        }

        public void LogError(Exception exception)
        {
            var stampedMsg = string.Format("[{0}] - {1}", DateTime.Now.TimeOfDay, exception.Message);

            if (task.BuildEngine != null)
            {
                task.BuildEngine.LogErrorEvent(new BuildErrorEventArgs("Error", "Error", "", 0, 0, 0, 0,
                                                                       stampedMsg, "Error", taskName));
            }
            else
            {
                WriteLine(stampedMsg,ConsoleColor.Red);
            }
        }

        private void WriteLine(string line, ConsoleColor textColor)
        {
            var orgColor = Console.ForegroundColor;
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine(line);
            Console.ForegroundColor = orgColor;
        }
    }
}
